<script lang="ts" setup>
import { SYS_USER_QUERY_APP } from '/@/api/modules/base/app-sys-user';
import { SYS_ORGAN_QUERY_APP } from '/@/api/modules/base/app-sys-organ';
import { ADDRESS_BOOK_USER_QUERY_APP } from '/@/api/modules/base/app-sys-user';
import { state, searchState } from './state';
import { onMounted, nextTick } from 'vue';
import { cloneDeep } from 'lodash';
import { Search2 as NutIconSearch2, Right as AppNutIconRight } from '@nutui/icons-vue-taro';
import { navigateTo, showLoading } from '@tarojs/taro';
import { setCallbackAndDDBackListener, back } from '/@/utils/back';

/**
 * 查询用户列表 根据组织id
 * @description 列表查询
 * @param page -当前页
 * @param pageSize -每页条数
 * @param name
 */
function queryList(
  page: number = 1,
  pageSize: number = 15,
  organId: string[] = [],
  name: string = '',
) {
  if (!page && state.finished) return;
  state.loading = true;
  showLoading();
  SYS_USER_QUERY_APP({
    comQuery: { page, pageSize },
    organId,
    name,
  })
    .then((res) => {
      state.loading = false;

      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.content || !res.content.length) return;

      res.content.forEach((item) => state.list.push(item));

      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;
  queryList(state.activePage, 15, [state.activeOrganId], state.name);
}

/**
 *
 * 根据选择的组织id查询用户列表
 */
function queryUserListBySelectedOrganId(activeOrganIds: string[]) {
  state.activePage = 1;
  state.finished = false;
  state.loading = false;
  state.list = [];
  state.activeOrganId = activeOrganIds[activeOrganIds.length - 1];
  onLoading();
}

onMounted(() => {
  //查询组织结构
  showLoading();
  SYS_ORGAN_QUERY_APP({ comQuery: { page: 1, pageSize: 10000 } }).then((res) => {
    state.sourceOrganTree = res.content;
    state.organTree = cloneDeep(state.sourceOrganTree);
  });
  //默认根组织结构
  state.selectedOrganTree = [];
  state.selectedOrganTree.push({
    name: '联系人',
  });
  //设置回调和钉钉back监听
  setCallbackAndDDBackListener(condition, queryUserByBack);
});
/**
 *  根联系人
 */
function condition() {
  return state.selectedOrganTree.length === 1;
}

/**
 * scrollView滚动到最右边
 */
function scrollViewToRight() {
  //子view渲染后才能滚动
  nextTick(() => {
    const dom = document.getElementById('scroll_view_container');
    const x = dom?.scrollWidth;
    if (dom && x) {
      dom.scrollLeft += x;
    }
  });
}

/**
 * 点击进入下一层
 * @param item 当前的item
 */
function next(item: AppSysOrgan.Dto) {
  state.organTree = item.children;
  state.selectedOrganTree.push(item);
  queryUserListBySelectedOrganId([item.id || '0']);
  scrollViewToRight();
}

/**
 * 点击back按钮 查询上一级用户
 *
 */
function queryUserByBack() {
  //返回上一层组织
  state.selectedOrganTree.pop();

  const size = state.selectedOrganTree.length;
  //size  === 0 根组织
  if (size === 1) {
    contactRoot();
    return;
  }
  let currentItem = state.selectedOrganTree[size - 1];
  state.organTree = currentItem.children;
  queryUserListBySelectedOrganId([currentItem.id || '0']);
}

/**
 * 根据用户名查询用户信息-用于搜索
 * @description 列表查询
 * @param page -当前页
 * @param pageSize -每页条数
 * @param name
 */
function queryUserList(page: number = 1, pageSize: number = 15) {
  if (!page && searchState.finished) return;
  searchState.loading = true;
  showLoading();
  ADDRESS_BOOK_USER_QUERY_APP({
    comQuery: { page, pageSize },
    keyword: searchState.keyword,
  })
    .then((res) => {
      searchState.loading = false;

      if (
        searchState.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      )
        searchState.finished = true;
      if (!res.users || !res.users.length) return;

      res.users.forEach((item) => searchState.list.push(item));

      searchState.activePage += 1;
    })
    .catch(() => {
      searchState.loading = false;
    });
}

/**
 *
 * @function 加载
 */
function onUserLoading() {
  if (searchState.finished) return;
  queryUserList(searchState.activePage, 15);
}

/**
 *
 * 根据选择的组织id查询用户列表
 */
function searchUser() {
  searchState.activePage = 1;
  searchState.finished = false;
  searchState.loading = false;
  searchState.list = [];
  onUserLoading();
  if (searchState.keyword) {
    searchState.visible = true;
  } else {
    searchState.visible = false;
  }
}

/**
 * 根据组织列表返回 xx-xx-xx 组织名称
 * @param organs 展示用户属于的组织名称例如： 部门1-子部门11-子部门111
 */
function organName(organs?: AppSysOrgan.Dto[]): string {
  let name = '';
  organs?.forEach((item, index) => {
    name += item.name;
    if (index != organs.length - 1) {
      name += '-';
    }
  });
  return name;
}
/**
 * 导航
 * @param index
 */
function navigation(index: number) {
  //删除选中组织的数量
  const count = state.selectedOrganTree.length - (index + 1);
  state.selectedOrganTree.splice(index + 1, count);

  //根联系人
  if (index === 0) {
    contactRoot();
    return;
  }

  let currentItem = state.selectedOrganTree[index];
  state.organTree = currentItem.children;
  queryUserListBySelectedOrganId([currentItem.id || '0']);
}

/**
 * 根联系人，只显示组织，不显示人员（人属于某个组织）
 */
function contactRoot() {
  state.activePage = 1;
  state.finished = false;
  state.loading = false;
  state.list = [];
  state.activeOrganId = '';
  state.organTree = state.sourceOrganTree;
}
</script>

<template>
  <view class="contacts-list app-page--1">
    <app-navbar title="通讯录" @handleBack="back()" :hookBack="true" />
    <nut-searchbar
      v-model="searchState.keyword"
      placeholder="输入姓名、联系号码搜索"
      @change="searchUser()"
    >
      <template v-slot:leftin>
        <nut-icon-search2 />
      </template>
    </nut-searchbar>
    <scroll-view
      class="horizontal-scroll-view"
      :scroll-x="true"
      :lower-threshold="100"
      id="scroll_view_container"
    >
      <view
        class="contacts-list__navigation-item"
        v-for="(item, index) in state.selectedOrganTree"
        :key="item.id"
        @click="navigation(index)"
      >
        <text :style="{ color: index === state.selectedOrganTree.length - 1 ? '#333' : '#507aee' }"
          >{{ item.name }}{{ index != state.selectedOrganTree.length - 1 ? '>' : '' }}</text
        >
      </view>
    </scroll-view>
    <scroll-view
      v-if="searchState.visible"
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onUserLoading()"
    >
      <view class="contacts-search__wrapper">
        <nut-cell-group>
          <nut-cell
            :title="item.user?.name || item.user?.nickName"
            :desc="organName(item.organs)"
            v-for="item in searchState.list"
            :key="item.user?.id"
            @click="navigateTo({ url: `/pages/contacts/detail/index?id=${item.user?.id}` })"
          />
        </nut-cell-group>
        <view class="app-page__list-tips">
          <text v-if="!searchState.list.length">暂无数据！</text>
          <text v-else-if="searchState.list.length && state.loading">加载中...</text>
          <text v-else-if="searchState.list.length && state.finished">加载完成!</text>
        </view>
      </view>
    </scroll-view>

    <scroll-view
      v-else
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoading()"
    >
      <view class="contacts-list__wrapper">
        <nut-cell-group>
          <nut-cell
            :title="item.name"
            v-for="item in state.organTree"
            :key="item.id"
            @click="next(item)"
          >
            <template v-slot:link>
              <app-nut-icon-right />
            </template>
          </nut-cell>
        </nut-cell-group>

        <nut-cell-group>
          <nut-cell
            class="contacts-list__user-select"
            :title="item.name || item.nickName"
            desc="选择"
            v-for="item in state.list"
            :key="item.id"
            @click="navigateTo({ url: `/pages/contacts/detail/index?id=${item.id}` })"
          />
        </nut-cell-group>
        <view class="app-page__list-tips">
          <text v-if="state.list.length && state.loading">加载中...</text>
          <text v-else-if="state.list.length && state.finished">加载完成!</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>
<style lang="scss">
@import './index.scss';
</style>
